<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 
      Vue2中，中央事件总线的操作手法：

        1. 先new一个空的 Vue 实例对象，eventBus
        2. 在A组件上通过 eventBus.$on() 订阅消息
        3. 在B组件上通过 eventBus.$emit() 触发消息

     -->

    <div id="app"></div>

    <script src="../lib/vue-2.js"></script>

    <script>
      const eventBus = new Vue();
      console.log("eventBus", eventBus);

      const Hello = {
        data() {
          return {
            count: 10,
          };
        },
        template: `
          <div>
            <p>Hello - {{ count }}</p>
          </div>
        `,
        created() {
          // 通过 eventBus.$on 来订阅消息
          eventBus.$on("abcd", (payload) => {
            console.log("abcd 被触发了", payload);
            this.count++;
          });
        },
        destroyed() {
          // 通过 eventBus.$off 来取消订阅
          eventBus.$off("abcd");
        },
      };

      const World = {
        template: `
          <div>
            <p>World</p>
            <button @click="fn1">Hello count++</button>
          </div>
        `,
        methods: {
          fn1() {
            // 通过 eventBus.$emit() 来发布消息
            eventBus.$emit("abcd", "张三");
          },
        },
      };

      const App = {
        el: "#app",
        data() {
          return {
            isShowHello: true,
          };
        },
        template: `
          <div>
            <Hello v-if="isShowHello" />

            <World />
          </div>
        `,
        components: {
          Hello,
          World,
        },
      };

      new Vue(App);
    </script>
  </body>
</html>
